package com.lmc.form.script;

import com.fasterxml.jackson.core.type.TypeReference;
import com.free.bsf.core.util.JsonUtils;
import com.free.bsf.core.util.StringUtils;
import lombok.val;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class EventScripts {

    public static class EventScript {
        public String name;
        public String description;
        public String action;
        public String time;//before,after
        public boolean use=true;//是否使用
        public List<Script> scripts = new ArrayList<>();

        public static class Script {
            public String condition;
            public String script;
        }
    }
    private List<EventScript> events = new ArrayList<>();
    public EventScripts(String script){
        //script="{name:'a',description:'b',action:'add',time:'before',scripts:[{condition:'form.bbb==1||form.ccc==2',script:'form.bbb=5;'}]}";
        events=JsonUtils.deserialize(script,new TypeReference<List<EventScript>>(){});
    }

    public String filter(String action,String time){
        val list = events.stream().filter((e)->action.equals(e.action)&&time.equals(e.time)&&e.use==true).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        for(val o:list){
            if(o.scripts!=null) {
                for (val s : o.scripts) {
                    if(!StringUtils.isEmpty(s.condition)) {
                        sb.append("if(" + s.condition + "){" + s.script + "\r\nreturn api.form;}");
                    }
                }
            }
        }
        return sb.toString();
    }
}
